package com.eqdd.yiqidian.ui.mine.pizhun;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;

import com.eqdd.yiqidian.MyPiZhunInfoActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.LizhiPizhunInfoResultBean;
import com.eqdd.yiqidian.bean.rebuild.LizhiShenpiStepListResultBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.subscribers.DisposableSubscriber;

public class MyPiZhunInfoActivity extends BaseActivity {
    private MyPiZhunInfoActivityCustom dataBinding;
    private ArrayList<Object> datas;
    private SlimAdapterEx slimAdapterEx;
    private String quitId;
    private SimpleDateFormat sf;
    private SimpleDateFormat sfUse;

    private int who;
    private int status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_my_pi_zhun_info);

    }

    private boolean checkParam() {
        if (dataBinding.rbAgree.isChecked()) {
            return true;
        } else if (dataBinding.rbReject.isChecked() && !TextUtils.isEmpty(dataBinding.etRemark.getText())) {
            return true;
        }
        return false;
    }

    @Override
    public void initData() {
        quitId = getIntent().getStringExtra("quitId");
        who = getIntent().getIntExtra(Config.WHO, 0);
        status = getIntent().getIntExtra(Config.STATUS, 0);
        initTitle();
        sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        sfUse = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        datas = new ArrayList<>();
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.recyclerView.setFocusable(false);
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_28, new SlimInjector<SlimEditHintBean>() {
            @Override
            public void onInject(SlimEditHintBean data, IViewInjector injector) {
                injector.text(R.id.tv_left_content, dealText(data.getTitle()))
                        .text(R.id.tv_right_hint_content, dealText(data.getContent()));
            }
        }).register(R.layout.list_item_31, new SlimInjector<LizhiShenpiStepListResultBean>() {
            private Date date;

            @Override
            public void onInject(LizhiShenpiStepListResultBean data, IViewInjector injector) {

                try {
                    date = sf.parse(data.getCreateTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                injector.text(R.id.tv_upper_left_content, sfUse.format(date))
                        .text(R.id.tv_upper_right_content, data.getDepartName() + " " + data.getPostName())
                        .text(R.id.tv_down_left_content, data.getStaffName())
                        .text(R.id.tv_down, data.getMessage());
            }
        }).attachTo(dataBinding.recyclerView);
    }

    private void initTitle() {


        initTopTitleBar(View.VISIBLE, who == 0 ? "离职单" : "离职审批");
        if (who >= 1 && status == 0) {
            initTopRightText("提交", v -> {
                if (checkParam()) {
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + (who == 1 ? HttpConfig.LIZHI_SHENPI_LEADER : HttpConfig.LIZHI_SHENPI_HR))
                            .params("userGuid", user.getGuid())
                            .params("quitId", quitId)
                            .params("message", TextUtils.isEmpty(dataBinding.etRemark.getText().toString()) ? "无备注信息" : dataBinding.etRemark.getText().toString())
                            .params("type", dataBinding.rbAgree.isChecked() ? 1 : 2)
                            .execute(new DialogCallBack<HttpResult>(this) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        setResult(Config.SUCCESS);
                                        finish();
                                    }
                                }
                            });
                } else {
                    ToastUtil.showShort("被拒绝好可怜，添加备注说明一下原因嘛！");
                }
            });
        }
    }

    private String dealText(String text) {
        return TextUtils.isEmpty(text) ? "" : text;
    }

    @Override
    public void setView() {
        showLoading();
        Flowable<HttpResult<LizhiPizhunInfoResultBean>> lizhiInfoFlow = OkGo.<HttpResult<LizhiPizhunInfoResultBean>>post(HttpConfig.BASE_URL + HttpConfig.LIZHI_INFO)
                .params("quitId", this.quitId)
                .converter(new JsonConverter<HttpResult<LizhiPizhunInfoResultBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<LizhiPizhunInfoResultBean>>());
        Flowable<HttpResult<List<LizhiShenpiStepListResultBean>>> lizhiStepFlow = OkGo.<HttpResult<List<LizhiShenpiStepListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.LIZHI_SHENPI_STEP_LIST_INFO)
                .params("quitId", this.quitId)
                .converter(new JsonConverter<HttpResult<List<LizhiShenpiStepListResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<List<LizhiShenpiStepListResultBean>>>());
        Flowable.combineLatest(lizhiInfoFlow, lizhiStepFlow, new BiFunction<HttpResult<LizhiPizhunInfoResultBean>, HttpResult<List<LizhiShenpiStepListResultBean>>, Object>() {
            @Override
            public Object apply(@NonNull HttpResult<LizhiPizhunInfoResultBean> lizhiPizhunInfoResultBeanHttpResult, @NonNull HttpResult<List<LizhiShenpiStepListResultBean>> listHttpResult) throws Exception {
                HttpResult<LizhiPizhunInfoResultBean> httpResult = lizhiPizhunInfoResultBeanHttpResult;
                if (httpResult.getStatus() == 200) {
                    LizhiPizhunInfoResultBean lizhiPizhunInfoResultBean = httpResult.getItems();
                    datas.add(new SlimEditHintBean("离职编码", lizhiPizhunInfoResultBean.getCode(), 0));
                    datas.add(new SlimEditHintBean("部门", lizhiPizhunInfoResultBean.getDepartment(), 1));
                    datas.add(new SlimEditHintBean("岗位", lizhiPizhunInfoResultBean.getPost(), 2));
                    datas.add(new SlimEditHintBean("公司名称", lizhiPizhunInfoResultBean.getCompany(), 3));
                    datas.add(new SlimEditHintBean("工号", lizhiPizhunInfoResultBean.getJobNumber(), 4));
                    datas.add(new SlimEditHintBean("入职时间", lizhiPizhunInfoResultBean.getJoinTime(), 5));
                    datas.add(new SlimEditHintBean("离职时间", lizhiPizhunInfoResultBean.getQuitTime(), 6));
                    datas.add(new SlimEditHintBean("离职类型", lizhiPizhunInfoResultBean.getQuitType(), 7));
                    datas.add(new SlimEditHintBean("名字", lizhiPizhunInfoResultBean.getUname(), 8));
                    datas.add(new SlimEditHintBean("离职原因", lizhiPizhunInfoResultBean.getQuitReason(), 9));
                    datas.add(new SlimEditHintBean("申请时间", lizhiPizhunInfoResultBean.getCreateTime(), 10));
                    if (who >= 1 && status == 0) {//非我，带审批
                        dataBinding.llDownRoot.setVisibility(View.VISIBLE);
                    }
                }
                datas.addAll(listHttpResult.getItems());
                slimAdapterEx.updateData(datas);

                return 1;
            }
        })
                .subscribe(disposable);
        dataBinding.rbReject.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbAgree.setChecked(!isChecked);
            }
        });
        dataBinding.rbAgree.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbReject.setChecked(!isChecked);
            }
        });
    }

    private DisposableSubscriber<Object> disposable = new DisposableSubscriber<Object>() {
        @Override
        public void onNext(Object o) {

        }

        @Override
        public void onError(Throwable t) {
            ToastUtil.showShort(Config.SERVER_ERROR);
            System.out.println(t.toString());
            hideLoading();
        }

        @Override
        public void onComplete() {
            hideLoading();
        }
    };

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}
